require 'rubygems'
require 'net/smtp'
require 'Net/DNS'

module BulkMail
  # Performs a DNS query for a domain's MX records and returns an array
  # of SMTP servers for the domain ordered by preference. If no records
  # are found an error is raised. 
  def self.smtp_servers_for_domain(domain)
    res = Net::DNS::Resolver.new
    mx = Net::DNS.mx(domain, res, 'IN')
    if mx
      mx.sort {|x,y| x.preference <=> y.preference}.map {|rr| rr.exchange}
    else
      raise RuntimeError, "Could not locate MX records for domain #{domain}."
    end
  end
end